package tech.popsoft.cip.api.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.web.client.RestTemplate;
import tech.popsoft.cip.api.entity.ApiRequest;
import tech.popsoft.cip.api.entity.ApiResponse;
import tech.popsoft.cip.api.handler.system.MessageQueryParameter;

import java.util.Date;
import java.util.Iterator;
import java.util.TreeMap;

/**
 * API服务测试
 * @author wqliu
 * @date 2022-10-2
 **/
@Slf4j
public class ApiRestControllerTest {

    private ApiRequest apiRequest;

    @Before
    public void init(){
        apiRequest=new ApiRequest();
        apiRequest.setAppCode("TMS");
        String requestTime = DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss");
        apiRequest.setRequestTime(requestTime);
        apiRequest.setSignMethod("MD5");



    }

    @Test
    public void MessageQueryTest(){

        apiRequest.setServiceCode("platform.message.query");
        MessageQueryParameter messageQueryParameter=new MessageQueryParameter();
        messageQueryParameter.setCount(5);
        apiRequest.setData(JSON.toJSONString(messageQueryParameter));
        apiRequest.setSign(generateSign(apiRequest));

        RestTemplate restTemplate=new RestTemplate();
        ApiResponse apiResponse = restTemplate.postForObject("http://localhost:8090/api/rest",apiRequest,
                ApiResponse.class);
        log.info(JSON.toJSONString(apiResponse));

    }


    public String generateSign(ApiRequest apiRequest){
        //参数进入map，并自动排序
        TreeMap<String, String> requestDataMap = new TreeMap<>();
        requestDataMap.put("appCode", apiRequest.getAppCode());
        requestDataMap.put("data", apiRequest.getData());
        requestDataMap.put("requestTime", apiRequest.getRequestTime());
        requestDataMap.put("serviceCode", apiRequest.getServiceCode());
        requestDataMap.put("signMethod", apiRequest.getSignMethod());
        //密钥 此处固化
        String appSecret = "8543692d-7ea7-4797-a746-47891bff2bec";

        //拼装参数与密钥
        StringBuffer sb = new StringBuffer();
        sb.append(appSecret);
        Iterator<String> iterator = requestDataMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            sb.append(key).append("=").append(requestDataMap.get(key));
        }
        sb.append(appSecret);
        String param = sb.toString();
        // 进行签名
        return  DigestUtils.md5Hex(param);
    }

}